<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="visible"
               v-loading="loading"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="80%">
      <el-form ref="formRefs"
               :model="formModel"
               :rules="formRules"
               label-width="120px">
        <el-form-item label="并症名称："
                      prop="name">
          <el-input v-model="formModel.name"
                    placeholder="请输入并症名称"
                    class="w-200"></el-input>
        </el-form-item>
        <el-form-item label="关联检测项："
                      prop="references">
          <el-select v-model="detectIds"
                     filterable
                     remote
                     clearable
                     reserve-keyword
                     placeholder="请输入检测项"
                     :remote-method="searchMethod"
                     :loading="loading1"
                     @change="handleSelectItems"
                     class="w-200">
            <el-option v-for="item in optionsFilterList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
          <el-button type="primary"
                     @click="handleAddDetect(detectIds)">新 增
          </el-button>
          <el-card class="mt-20">
            <div slot="header">已选检测项</div>
            <el-table :data="references"
                      border
                      style="width: 100%">
              <el-table-column prop="deviceName"
                               label="项目名称">
              </el-table-column>
              <el-table-column prop="referenceName"
                               label="检测指标">
              </el-table-column>
              <el-table-column prop="result"
                               label="结果">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.resultArr"
                             placeholder="请选择判断结果"
                             class="w-200"
                             multiple>
                    <el-option v-for="item in scope.row.resultSet"
                               :key="item"
                               :label="item"
                               :value="item"
                               class="w-200">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="condition"
                               label="条件">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.condition"
                             placeholder="请选择条件"
                             class="w-200">
                    <el-option v-for="item in conditionList"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="errorCount"
                               label="异常次数">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.errorCount"
                            placeholder="请输入异常次数"
                            class="w-200"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="删 除"
                               width="120">
                <template slot-scope="scope">
                  <el-button type="danger"
                             @click="delRow(references, scope.$index, 'detect')">删 除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

          </el-card>
        </el-form-item>

        <el-form-item label="条件判断：" required v-if="references.length>0">
          <el-button type="primary" @click="handleAddCondition">增 加</el-button>
        </el-form-item>

        <el-form-item v-for="(item,index) in formModel.judges" v-if="references.length>0" :key="index+'judge'">
          <el-select v-model="item.localIds"
                     clearable
                     multiple
                     style="width: 360px"
                     placeholder="请选择条件">
            <el-option v-for="item in references"
                       :key="item.localId"
                       :label="item.referenceName"
                       :value="item.localId">
            </el-option>
          </el-select>
          <el-select v-model="item.conditionType"
                     clearable
                     style="width: 220px"
                     placeholder="请选择满足条件">
            <el-option v-for="item in satisfyList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>

          <el-button type="danger" @click="handleDelCondition(index)">删 除</el-button>
        </el-form-item>


      </el-form>
      <p align="center">
        <el-button type="info"
                   @click="modalClose">返 回
        </el-button>
        <el-button type="primary"
                   @click="submitForm">保 存
        </el-button>
      </p>
    </el-dialog>
  </div>
</template>
<script>
import {mapGetters} from 'vuex'
import VueNeditorWrap from 'vue-neditor-wrap'

export default {
  name: '', // 合并症管理弹窗
  props: {
    dataObj: {
      type: Object,
      default: {}
    },
    visible: {
      type: Boolean,
      default: false
    },
    getList: {
      type: Function,
      default: null
    },
  },
  data() {
    return {
      title: '新 增',
      loading: false,
      loading1: false,
      formModel: {
        name: '', // 并症名称
        references: [], // 推荐检测项
        knowledgePoints: '', // 病症知识点
        confirmAgain: 0, // 确认并发症
        recommendableProjects: '', // 推荐医院检查项目
        themeHealthDtoList: [], // 已选健康筛查项目列表
        apparatusRequestDtoList: [], // 推荐器械列表
        sellDrugDtoList: [], // 推荐商品列表
        recommendSalesScript: '', // 销售话术
        judges: []
      },
      references: [],
      detectIds: '', // 推荐检测项
      formRules: {
        name: [{required: true, message: '请输入并症名称', trigger: 'blur'}],
        knowledgePoints: [{required: true, message: '请输入病症知识点', trigger: 'blur'}],
      },
      optionsList: [],
      optionsFilterList: [],
      conditionList: [
        {id: 0, name: '间隔0天'},
        {id: 1, name: '间隔1天'},
      ],
      satisfyList: [
        {
          name: '全部满足',
          id: 1
        }, {
          name: '任何一满足',
          id: 2
        }, {
          name: '满足任何两个',
          id: 3
        }],
      // 推荐健康风险筛查项目
      riskList: [],
      riskFilterList: [],
      riskIds: [], // 推荐健康风险筛查项目
      equipmentDataObj: {}, // 推荐器械
      shopDataObj: {}, // 推荐商品
      medicineDataObj: {}, // 联合荐药
      tableDetect: [], // 已选检测项
      childMedicineTableData: []
    }
  },
  methods: {
    modalClose() {
      this.$emit('update:visible', false); // 直接修改父组件的属性
    },
    //新增条件
    handleAddCondition() {
      this.formModel.judges.push({
        localIds: [],
        conditionType: ''
      })

    },
    //删除条件
    handleDelCondition(index) {
      this.formModel.judges.splice(index, 1)
    },
    // 搜索联检测项
    searchMethod(query) {
      if (query !== '') {
        let _this = this;
        _this.loading1 = true; // 锁住
        this.post(this.api.promote.getDeviceList, {
          name: query,
          pageIndex: 0,
          pageSize: 10
        }).then(res => {
          if (res.data.code === '200') {
            _this.loading1 = false;
            _this.optionsList = res.data.object;
          }
        })

        /**
         * 搜索内容渲染到下拉框
         * 从 this.optionsList 把数据赋值到 this.optionsFilterList
         * 只有这样才能起作用
         */
        setTimeout(() => {
          _this.loading1 = false;
          _this.optionsFilterList = _this.optionsList.filter(item => item.name.indexOf(query) > -1);
        }, 200);
      } else {
        this.optionsFilterList = [];
      }
    },
    // 增加推推荐检测项
    handleAddDetect(selVal) {
      if (selVal === '') {
        this.$message.error('请选择关联检测项!');
        return
      }

      if (this.references.some(item => item.deviceId === selVal)) {
        this.$message.error('推荐检测项不能重复添加!');
        this.detectIds = '';
        return
      }
      this.getReferenceInfo(selVal)
    },
    getReferenceInfo(deviceId) {
      this.post(this.api.promote.getReferenceInfo, {deviceId: deviceId})
        .then(res => {
          if (res.data.code === '200') {
            let resData = res.data.object;
            this.detectIds = '';
            resData.forEach(item => {
              //新增一个条件ID
              this.$set(item, 'localId', item.referenceId)
              if (item.resultSet.length > 0) {
                this.references.push(item);
              }
            })
            if (resData.some(el => el.resultSet.length === 0)) {
              this.$message.error('该检测项目未配置检测结果判断!');
              return;
            }
          }

        })
    },
    // 选中关联检测项
    handleSelectItems(item) {
      this.detectIds = item;
    },
    // 提交
    submitForm() {
      this.$refs['formRefs'].validate((valid) => {
        if (valid) {
          if (this.references.length === 0) {
            this.$message.error('请选择关联检测项!');
            return
          }
          this.formModel.references = this.references.map(item => ({
            ...item,
            result: JSON.stringify(item.resultArr)
          }));
          this.post(this.api.healthMap.updateHealthMapArteriosclerosis, this.formModel, {showFullScreenLoading: true}).then(res => {
            if (res.data.code === '200') {
              this.$message.success('保存成功!');
              this.modalClose();
              this.$parent.getList();
            }
          })

        }
      })
    },

    delRow(table, index, option) {
      let localId = table[index].localId;
      this.formModel.judges.forEach(item => {
        item.localIds.forEach(ids => {
          if (localId == ids) {
            item.localIds = item.localIds.filter(f => f != ids)
          }
        })
      })
      table.splice(index, 1);
    },


    // 远程搜索推荐健康风险筛查项目
    remoteMethod(query) {
      if (query !== '') {
        let _this = this;
        _this.loading1 = true;
        this.post(this.api.promote.getRecommendPageList, {
          name: query
        }).then(res => {
          if (res.data.code === '200') {
            _this.loading1 = false;
            _this.riskList = res.data.object.map(item => ({
              healthCheckPackageId: item.id,
              name: item.name,
              type: item.healthRiskTypeName
            }));
          }
        })
        setTimeout(() => {
          _this.loading1 = false;
          _this.riskFilterList = _this.riskList.filter(item => item.name.indexOf(query) > -1);
        }, 200)
      } else {
        this.riskFilterList = [];
      }
    },
    // 选择推荐健康风险筛查项目
    handleSelect(item) {
      this.riskIds = item;
    },

    // 删除已选健康筛查项目
    delRisk(table, index) {
      table.splice(index, 1);
    },

    // 查询详情
    getDetail() {
      this.post(this.api.healthMap.getHealthMapArteriosclerosisDetail, {
        id: this.dataObj.id
      }).then(res => {
        if (res.data.code === '200') {
          let resData = res.data.object;
          this.references = resData.references.map(item => ({
            ...item,
            resultArr: item.result === '' ? [] : JSON.parse(item.result),
          }))
          resData.references = this.references;
          this.references.forEach(item => {
            this.$set(item, 'localId', item.referenceId)
          })
          this.formModel = Object.assign(this.formModel, resData);

          // 关联检测项
          let deviceIds = [...new Set(this.references.map(item => item.deviceId))];
          let arr = [];
          deviceIds.forEach(async item => {
            const {data: result} = await this.post(this.api.promote.getReferenceInfo, {deviceId: item});
            if (result.code === '200') {
              result.object.forEach(list => {
                arr.push(list.resultSet);
              })
              this.references.forEach((el, index) => {
                this.$set(el, 'resultSet', arr[index]);
              })
            }
          });
        }
      })
    }
  },
  created() {
    if (this.dataObj) {
      this.title = '编 辑';
      if (this.dataObj.id) {
        this.getDetail();
      } else {
        this.formModel.name = this.dataObj.name;
      }
    }
  },
  components: {
    VueNeditorWrap
  },
  computed: {
    ...mapGetters(['fileUpload'])
  }
}
</script>
<style scoped lang="scss">
.w-500 {
  width: 500px;
}

.table-cell {
  td {
    padding: 3px 10px;
    border-bottom: 1px solid #ebeef5;
    border-right: 1px solid #ebeef5;

    &.first-td {
      border-left: 1px solid #ebeef5;
    }
  }
}
</style>
